import http from 'axios'
import router from "@/common/router";
import store from "./store";
import {Message} from 'element-ui'

//用来获取调用此js的vue组件实例（this）
let that = null;
let sendThis = (_this)=> { // eslint-disable-line no-unused-vars
    that = _this;
};

//带验证跳转路由
let navigate = (url)=>{ // eslint-disable-line no-unused-vars
    let userId = store.state.userId
    if(!(userId && userId!=='undefined')){
        store.commit('clearStore');
        that.getImageCodeBase64()
        that.loginVisible = true
    }else{
        router.push(url)
    }
}

//基础Url
http.defaults.baseURL = store.state.baseUrlApi
//使用代理时或者将打包后的项目集成到后台时这么配置
// http.defaults.baseURL = '/api/'
//请求超时时间
http.defaults.timeout = 100000;

//弹框标记
let msgFlag=false;

//--------------------------------Axios配置拦截----------------------------------------

http.interceptors.request.use((config)=>{
    let token = store.state.token
    if(token){
        config.headers.common[store.state.tokenKey] = token
    }
    return config
},(error)=>{
    Message.error("request："+error)
    return Promise.reject(error)
})

http.interceptors.response.use((response)=>{
    // 如果验证码的key在头部,在这里将验证码取出，放在缓存中
    // if(response.headers.captcha_token){
    //     //将验证码的token存到缓存
    //     store.commit('set_vertoken',response.headers.captcha_token)
    // }
    return response
},(error)=>{
    if(error.response){
        switch (error.response.status) {
            case 1001:{
                error.message = "未登陆，请先登陆！";
                router.push('/login')
            }break;
            case 401:{
                error.message = "Token验证错误！";
                router.push('/login')
            }break;
            case 402:{
                error.message = "402错误："+error;
            }break;
            case 403:{
                error.message = "对不起，您没有权限操作！";
            }break;
            case 404:{
                error.message = "页面丢失！";
                router.push('/404')
            }break;
            case 500:{
                error.message = "服务器异常："+error;
                router.push('/500')
            }break;
            default:{
                error.message = "未知异常："+error;
            }break;
        }
    }else{
        Message.error("服务器未启用："+error)
    }
    //解决Token失效多次弹框问题
    if(!msgFlag){
        Message.error(error.message)
        msgFlag=true;
        setTimeout(()=>{
            msgFlag=false
        },3000)
    }
    return Promise.reject(error)
})

//--------------------------------Axios配置拦截----------------------------------------

//导出多个（属性/方法）
export {http,sendThis,navigate}
//注意在其他文件导入时需要
//import {sendThis} form './'
